home *** CD-ROM | disk | FTP | other *** search
/ Hardcore Visual Basic 5.0 (2nd Edition) / Hardcore Visual Basic 5.0 - Second Edition (1997)(Microsoft Press).iso / Code / SIEVEB~1.CLS < prev    next >
Text File  |  1997-06-14  |  2KB  |  76 lines

  1. VERSION 1.0 CLASS
  2. BEGIN
  3.   MultiUse = -1  'True
  4. END
  5. Attribute VB_Name = "CSieveBasDllN"
  6. Attribute VB_GlobalNameSpace = False
  7. Attribute VB_Creatable = True
  8. Attribute VB_PredeclaredId = False
  9. Attribute VB_Exposed = True
  10. Attribute VB_Description = "Sieve of Eratosthenes"
  11. Option Explicit
  12.  
  13. Private af() As Boolean, iCur As Integer
  14. Private iMaxPrime As Integer, cPrime As Integer
  15.  
  16. Private Sub Class_Initialize()
  17.     ' Default size is largest integer
  18.     iMaxPrime = 32766
  19.     ReInitialize
  20. End Sub
  21.  
  22. Sub ReInitialize()
  23.     ReDim af(0 To iMaxPrime)
  24.     iCur = 1: cPrime = 0
  25. End Sub
  26.  
  27. Property Get NextPrime() As Integer
  28.     NextPrime = 0
  29.     ' Loop until we find a prime or overflow array
  30.     iCur = iCur + 1
  31.     On Error GoTo OverMaxPrime
  32.     Do While af(iCur)
  33.         iCur = iCur + 1
  34.     Loop
  35.     ' Cancel multiples of this prime
  36.     Dim i As Long
  37.     For i = iCur + iCur To iMaxPrime Step iCur
  38.         af(i) = True
  39.     Next
  40.     ' Count and return it
  41.     cPrime = cPrime + 1
  42.     NextPrime = iCur
  43. OverMaxPrime:       ' Array overflow comes here
  44. End Property
  45.  
  46. Property Get MaxPrime() As Integer
  47.     MaxPrime = iMaxPrime
  48. End Property
  49.  
  50. Property Let MaxPrime(iMaxPrimeA As Integer)
  51.     iMaxPrime = iMaxPrimeA
  52.     ReInitialize
  53. End Property
  54.  
  55. Property Get Primes() As Integer
  56.     Primes = cPrime
  57. End Property
  58.  
  59. Sub AllPrimes(ai() As Integer)
  60.     If LBound(ai) <> 0 Then Exit Sub
  61.     iMaxPrime = UBound(ai)
  62.     cPrime = 0
  63.     Dim i As Integer
  64.     For iCur = 2 To iMaxPrime
  65.         If Not af(iCur) Then    ' Found a prime
  66.             For i = iCur + iCur To iMaxPrime Step iCur
  67.                 af(i) = True    ' Cancel its multiples
  68.             Next
  69.             ai(cPrime) = iCur
  70.             cPrime = cPrime + 1
  71.         End If
  72.     Next
  73.     ReDim Preserve ai(0 To cPrime) As Integer
  74.     iCur = 1
  75. End Sub
  76.